﻿#region [ProcessUtil Using Statements]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
#endregion

namespace WP7_XNA_Accelerometer_Simulator.Utils.Interoperability
{
    /// <summary>
    /// This Class enables you to terminate other processes
    /// </summary>
    public static class ProcessUtil
    {
        #region [ProcessUtil Fields]
        static string ConsoleAppProcName = "AccelerometerServer";
        static string SilverlightOOBAppProcName = "sllauncher";
        #endregion

        #region [ProcessUtil Public Methods]
        /// <summary>
        /// Closes all the processes that won't be needed when the
        /// Simulator is terminated
        /// </summary>
        public static void CloseAccelerometerKit()
        {
            CloseAllInstances(SilverlightOOBAppProcName);
            CloseAllInstances(ConsoleAppProcName);
        }
        #endregion

        #region [ProcessUtil Private/Auxiliary Methods]
        /// <summary>
        /// Closes all the instances of a process
        /// </summary>
        /// <param name="processName">The process name</param>
        private static void CloseAllInstances(string processName)
        {
            Process[] processList = Process.GetProcessesByName(processName);

            try
            {
                if (processList.Count() != 0)
                {
                    foreach (Process proc in processList)
                    {
                        proc.CloseMainWindow();
                        proc.WaitForExit();

                        Console.WriteLine("Closed all running instances of " + processName);
                    }
                }
                else
                {
                    Console.WriteLine("No instances of" + processName + "running.");
                }
            }
            catch (System.NullReferenceException)
            {
                Console.WriteLine("No instances of " + processName + " running.");
            }
        }
        #endregion

    }
}
